package logic

import (
	"context"
	"errors"
	"regi-manage/model/cache"
	"regi-manage/model/mysql"
	"regi-manage/pkg"

	"regi-manage/regirpc/internal/svc"
	"regi-manage/regirpc/regirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *regirpc.RegisterRequest) (*regirpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User

	mysql.DB.Debug().Where("account = ?", in.Account).Find(&users)
	if users.ID != 0 {
		return nil, errors.New("当前账号已存在，请更换")
	}

	result, _ := cache.Rdb.Get(l.ctx, "cache_"+in.Tel).Result()
	if result != in.Code {
		return nil, errors.New("图形验证码错误")
	}

	user := mysql.User{
		Account:  in.Account,
		Password: pkg.MD5(in.Password),
		Tel:      in.Tel,
		Code:     in.Code,
	}

	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, err
	}

	return &regirpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
